package com.joelemon.mockinfluxdbdata.mock.boss;

import com.joelemon.mockinfluxdbdata.mock.wokers.DBInsertWokerService;

/**
 * @Description: 调用主线程
 * @Author: HJY
 * @Date: 2024/1/5
 */
public class BossRunner {
    private boolean started = false;
    private volatile boolean terminated = false;
    private DBInsertWokerService insertWokerService;

    private Thread bossThread;

    public BossRunner(DBInsertWokerService insertWokerService) {
        this.insertWokerService = insertWokerService;
    }

    public synchronized void start() {
        if (started) return;
        started = true;
        terminated = false;
        bossThread = new Thread(() -> {
            while (!terminated) {
                insertWokerService.syncJob();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            started = false;
        });
        bossThread.start();
    }

    public void stop() {
        // 线程停止
        terminated = true;
        bossThread.interrupt();
        // 执行clear
        insertWokerService.clear();
    }
}
